//
//  IntegralViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/24.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "IntegralRecordViewController.h"
#import "IntegralRecordTableViewCell.h"

static NSString *CellIdentifier =@"IntegralRecordTableViewCell";

@interface IntegralRecordViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic)  NSMutableArray *integralRecordArray;
@end

@implementation IntegralRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _integralRecordArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    
}


- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];

}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.integralRecordArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 48*VerticalRatio();
}

//定义 UITableView cell 的头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 14*VerticalRatio();
}

//定义 UITableView cell 的头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    IntegralRecordTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[IntegralRecordTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    
    NSString *integralRecordStr = [NSString stringWithFormat:@"%@,%@：%@"
                                                 ,self.integralRecordArray[indexPath.row][@"miflCreateTime"]
                                                 ,self.integralRecordArray[indexPath.row][@"miflRemark"]
                                                 ,self.integralRecordArray[indexPath.row][@"miflAmount"]];
    NSString *miflAmount = [NSString stringWithFormat:@"%@",self.integralRecordArray[indexPath.row][@"miflAmount"]];
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:integralRecordStr];
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.565 blue:0.000 alpha:1.000] range:NSMakeRange(noteStr.length-miflAmount.length, miflAmount.length)];

    [cell.IntegralRecordLable setAttributedText:noteStr];

    
    return cell;
}

#pragma mark - 返回
- (IBAction)back:(id)sender {
    [self backBtn];
}
#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIntegralTecord];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.integralRecordArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIntegralTecord];
        });
    }
    
}


#pragma mark  === 获取兑换记录
- (void)getIntegralTecord {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
     [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMemberIntegrationFlow withHttpType:@"POST" withTag:HK_HK_queryMemberIntegrationFlow];
}




#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];

    if (tag == HK_HK_queryMemberIntegrationFlow){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.integralRecordArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.integralRecordArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
